<template>
  <el-card>
    <el-button type="primary" @click="openCreate">新建文章</el-button>
    <el-table :data="articles" style="width: 100%; margin-top: 20px;">
      <el-table-column type="index" prop="id" label="编号" width="60"/>
      <el-table-column prop="title" label="标题"/>
      <el-table-column prop="status" label="状态"/>
      <el-table-column prop="view_count" label="浏览量"/>
      <el-table-column prop="created_at" label="创建时间">
        <template #default="scope">
          {{ timeFormat(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button size="small" @click="viewArticle(scope.row)">预览</el-button>
          <el-button size="small" @click="editArticle(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="removeArticle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<!-- 文章列表页面 -->
<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { fetchDraftArticles, deleteArticle } from '@/api/article'
import formatTime from '@/utils/timeFormat'

// 时间格式化
const timeFormat = (time) => {
  return formatTime(time)
}
const articles = ref([])
const router = useRouter()
const viewArticle = (row) => {
  router.push({ path: '/article/view', query: { id: row.id } })
}
const loadArticles = async () => {
  const res = await fetchDraftArticles()
  articles.value = res.data
}

const openCreate = () => {
  router.push('/articles/edit')
}

const editArticle = (row) => {
  router.push({ path: '/articles/edit', query: { id: row.id } })
}

const removeArticle = async (id) => {
  await deleteArticle(id)
  loadArticles()
}

onMounted(loadArticles)
</script>
